package com.ibm.cps.processors.window;

import java.util.LinkedList;
import java.util.Queue;

import com.ibm.cps.message.ParsedDataMessage;

public class TimeBasedBuffer {
	private final Queue<ParsedDataMessage> buffer = new LinkedList<>();
	
	private final long windowSize;
	private long currentNewestTime = -1L;
	
	public TimeBasedBuffer(long windowSize) {
		this.windowSize = windowSize;
	}

	public boolean isFull(){
		if(buffer.isEmpty())
			return false;
		long oldestTime = buffer.peek().getTimestamp();
		return currentNewestTime - oldestTime > windowSize;
	}
	
	public void push(ParsedDataMessage message){
		buffer.offer(message);
		currentNewestTime = message.getTimestamp();
	}
	
	public void moveForward(long step){
		if(buffer.isEmpty())
			return;
		long newTargetOldestTime = currentNewestTime + step - windowSize;
		while(!buffer.isEmpty()){
			long oldestTime = buffer.peek().getTimestamp();
			if(oldestTime < newTargetOldestTime){
				buffer.poll();
			}else{
				return;
			}
		}
	}

	public Queue<ParsedDataMessage> getBufferedData() {
		return buffer;
	}
	
	public int size(){
		return buffer.size();
	}

}
